package com.wave.traffic.task;

import cn.hutool.core.util.NumberUtil;
import com.wave.traffic.enums.NetControllerEnum;
import com.wave.traffic.util.SocketClientUtil;
import com.wave.traffic.util.TimerUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;

/***
 * @Description 网络控制器任务
 * @Author chenjian
 * @Date 2022/9/16 15:55
 */
public class NetControllerTask extends Thread {
    private final static Logger logger = LoggerFactory.getLogger(NetControllerTask.class);

    private String ip;

    private int port;

    private ServerInfo serverInfo;

    public ServerInfo getServerInfo() {
        return serverInfo;
    }

    public void setServerInfo(ServerInfo serverInfo) {
        this.serverInfo = serverInfo;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public NetControllerTask(String ip, int port, ServerInfo serverInfo) {
        this.ip = ip;
        this.port = port;
        this.serverInfo = serverInfo;
    }

    @Override
    public void run() {
        try {
            Socket netController1 = new Socket(serverInfo.getServerIP1(), serverInfo.getServerPort1());
            Socket netController2 = new Socket(serverInfo.getServerIP2(), serverInfo.getServerPort2());
            Socket netController3 = new Socket(serverInfo.getServerIP3(), serverInfo.getServerPort3());
            //读取DI主动上报的信息
            Socket s = new Socket(ip, port);
            OutputStream os = s.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(os);
            DataOutputStream dos = new DataOutputStream(bos);
            InputStream is = s.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] bytes = new byte[10]; // 一次读取一个byte
            String ret = "";

            //实现读功能
            String str;
            while (true) {
                logger.info("AAAAAAAAAA");
                bis.read(bytes);
                ret += bytesToHexString(bytes) + " ";  //调用字节转化16进制字符串方法
                if (!StringUtils.isEmpty(ret)) {//有人要通行
                    //获取雷视摄像头感应道路是否有车的结果
                    boolean hasCar = HKCameraTask.hasCar;
                    logger.info("有人要通行,道路是否有车：" + hasCar);
                    str = ret;
                    str = str.trim();
                    String[] strs = str.split(",");
                    String lastPart = strs[strs.length - 1];
                    int lastPartInt = NumberUtil.parseInt(lastPart);
                    logger.info("闸机是否有人：" + lastPartInt);
                    if ((lastPartInt == 1) && !hasCar) {
                        logger.info("控制器打开人行绿灯,打开车辆红灯");

                        SocketClientUtil.sendData(netController1, NetControllerEnum.WRITE_DO1_CLOSE_COMMAND.getCode());
                        logger.info("控制器打开人行绿灯,打开车辆红灯-213-1");
                        SocketClientUtil.sendData(netController1, NetControllerEnum.WRITE_DO2_OPEN_COMMAND.getCode());
                        logger.info("控制器打开人行绿灯,打开车辆红灯-213-2");
                        //剩余两个网络控制器控制的人行灯切换成绿灯
                        SocketClientUtil.sendData(netController2, NetControllerEnum.WRITE_DO1_OPEN_COMMAND.getCode());
                        logger.info("人行灯切换成绿灯-212");
                        SocketClientUtil.sendData(netController3, NetControllerEnum.WRITE_DO1_OPEN_COMMAND.getCode());
                        logger.info("人行灯切换成绿灯-215");
                        //新建20s的延时任务，20s后所有人行灯切换成红灯，交通灯切换成绿灯
                        logger.info("发送延时任务");
                        TimerUtil.call(netController1, netController2, netController3, 30000L);
                    }
                    ret = "";
                }
            }
        } catch (Exception e) {
            logger.error("netControllerTask throws exception is {}", e.getMessage(), e);
        }
    }

    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            stringBuilder.append("0x");

            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
            if (i != src.length - 1) {
                stringBuilder.append(",");

            }
        }
        return stringBuilder.toString();
    }

}
